<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// ------------------------------------------------------------------------
/*
 * ------------------------------------------------------
 *  设置核心版本
 * ------------------------------------------------------
 */
$_ENV['XJ_PHP'] = 'XJPHP RESTful';
$_ENV['XJ_VERSION'] = '1.2.0';
// ------------------------------------------------------------------------
/*
 * ------------------------------------------------------
 *  设置相关目录
 * ------------------------------------------------------
 */
$application_folder_old = $application_folder;
// The path to the "application" directory
if (is_dir($application_folder))
{
	if (($_temp = realpath($application_folder)) !== FALSE)
	{
		$application_folder = $_temp;
	}
	else
	{
		$application_folder = strtr(
				rtrim($application_folder, '/\\'),
				'/\\',
				DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
		);
	}
}
elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
{
	$application_folder = BASEPATH.strtr(
			trim($application_folder, '/\\'),
			'/\\',
			DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
	);
}
else
{
	header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
	echo 'Your application folder path ['.$application_folder.'] does not appear to be set correctly. Please open the following file and correct this: '.SELF;
	exit(3); // EXIT_CONFIG
}
$_ENV['XJ_APPPATH'] =  $application_folder.DIRECTORY_SEPARATOR;

// The path to the "public" directory
if (is_dir($public_folder))
{
	if (($_temp = realpath($public_folder)) !== FALSE)
	{
		$public_folderv = $_temp;
	}
	else
	{
		$public_folder = strtr(
				rtrim($public_folder, '/\\'),
				'/\\',
				DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
		);
	}
}
elseif (is_dir(BASEPATH.$public_folder.DIRECTORY_SEPARATOR))
{
	$public_folder = BASEPATH.strtr(
			trim($public_folder, '/\\'),
			'/\\',
			DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
	);
}
$_ENV['XJ_PUBPATH'] = $public_folder.DIRECTORY_SEPARATOR;

/*
 * ------------------------------------------------------
 *  Set Config Database PATH
 *  $_ENV['XJ_CONFIG_DATABASE_PATH']
 * ------------------------------------------------------
 */
if (! isset($_ENV['XJ_CONFIG_DATABASE_PATH']))
	$_ENV['XJ_CONFIG_DATABASE_PATH'] = array();

if (is_file($file_path = $_ENV['XJ_PUBPATH'].'config/database.php'))
{
	if (! in_array($file_path, $_ENV['XJ_CONFIG_DATABASE_PATH']))
		array_push($_ENV['XJ_CONFIG_DATABASE_PATH'], $file_path);
}

if (is_file($file_path = $_ENV['XJ_APPPATH'].'config/database.php'))
{
	if (! in_array($file_path, $_ENV['XJ_CONFIG_DATABASE_PATH']))
		array_push($_ENV['XJ_CONFIG_DATABASE_PATH'], $file_path);
}

if (isset($_ENV['XJ_ENV']) AND is_file($file_path = $_ENV['XJ_APPPATH'].'config/'.$_ENV['XJ_ENV'].'/database.php'))
{
	if (! in_array($file_path, $_ENV['XJ_CONFIG_DATABASE_PATH']))
		array_push($_ENV['XJ_CONFIG_DATABASE_PATH'], $file_path);
}
/*
 * ------------------------------------------------------
*  Set Model Directory  PATH
*  $_ENV['XJ_MODEL_DIR_PATH']
* ------------------------------------------------------
*/
if (! isset($_ENV['XJ_MODEL_DIR_PATH']))
	$_ENV['XJ_MODEL_DIR_PATH'] = array();

if (is_dir($dir_path = $_ENV['XJ_PUBPATH'].'models'))
{
	if (! in_array($dir_path, $_ENV['XJ_MODEL_DIR_PATH']))
		array_unshift($_ENV['XJ_MODEL_DIR_PATH'], $dir_path);
}

if (is_dir($dir_path = $_ENV['XJ_APPPATH'].'models'))
{
	if (! in_array($dir_path, $_ENV['XJ_MODEL_DIR_PATH']))
		array_unshift($_ENV['XJ_MODEL_DIR_PATH'], $dir_path);
}

/*
 * ------------------------------------------------------
*  Set APP PATH
*  $_ENV['XJ_APP_DIR_PATH_ARR']
* ------------------------------------------------------
*/
if (! isset($_ENV['XJ_APP_DIR_PATH_ARR']))
	$_ENV['XJ_APP_DIR_PATH_ARR'] = array();

if (is_dir($dir_path = BASEPATH.'xj_core'.DIRECTORY_SEPARATOR))
{
	if (! in_array($dir_path, $_ENV['XJ_APP_DIR_PATH_ARR']))
		array_unshift($_ENV['XJ_APP_DIR_PATH_ARR'], $dir_path);
}

if (is_dir($dir_path = $_ENV['XJ_PUBPATH']))
{
	if (! in_array($dir_path, $_ENV['XJ_APP_DIR_PATH_ARR']))
		array_unshift($_ENV['XJ_APP_DIR_PATH_ARR'], $dir_path);
}

if (is_dir($dir_path = $_ENV['XJ_APPPATH']))
{
	if (! in_array($dir_path, $_ENV['XJ_APP_DIR_PATH_ARR']))
		array_unshift($_ENV['XJ_APP_DIR_PATH_ARR'], $dir_path);
}
// ------------------------------------------------------------------------
/*
 * ------------------------------------------------------
 *  Load the global functions （加载全局方法）
 * ------------------------------------------------------
 */
require_once(BASEPATH.'xj_core'.DIRECTORY_SEPARATOR.'Common.php');

/*
 * ------------------------------------------------------
 *  第一次调用初始化 URI
 * ------------------------------------------------------
 */
if (!isset($uri)){
	$uri    = FALSE;
	$class  = 'Index';
	$method = 'Get'; //REQUEST_METHOD
	$id = FALSE;
	if (isset($_SERVER["PATH_INFO"])){
		$uri = $_SERVER["PATH_INFO"];
	}elseif (isset($_SERVER["ORIG_PATH_INFO"])){
		$uri = $_SERVER["ORIG_PATH_INFO"];
	}
	if (isset($_SERVER["REQUEST_METHOD"])){
		$method = ucfirst($_SERVER["REQUEST_METHOD"]);
	}
	$uri_old = $uri;
}
/*
 * ------------------------------------------------------
 *  解析 CLASS，METHOD，ID
 * ------------------------------------------------------
 */
if ($uri !== FALSE){
	$path_arr = explode("/", $uri);

	if (is_array($path_arr) && count($path_arr) > 1){
		$class = ucfirst($path_arr[1]);
	}
	$id = '';
	if (is_array($path_arr) && count($path_arr) > 2){
		$id = $path_arr[2];
	}
	if ($method === FALSE){
		if (isset($_SERVER["REQUEST_METHOD"])){
			$method = ucfirst(strtolower($_SERVER["REQUEST_METHOD"]));
		}else{
			$method = "Get";
		}
	}
	$parameter = array();
	array_push($parameter, $id);
	for ($i = 3 ; $i < count($path_arr); $i++ ){
		if ($i % 2 == 1){
			$method = $method.ucfirst(strtolower($path_arr[$i]));
		}else{
			array_push($parameter, $path_arr[$i]);
		}
	}
	//if (is_array($path_arr) && count($path_arr) > 3){
		$id = $parameter;
	//}
}

// ------------------------------------------------------------------------

/*
 * ------------------------------------------------------
 *  Load the routes.php file.（加载本级应用目录下路由配置文件）
 * ------------------------------------------------------
 */
if (isset($_ENV['XJ_ENV']) AND is_file($_ENV['XJ_APPPATH'].'config/'.$_ENV['XJ_ENV'].'/routes.php'))
{
	include($_ENV['XJ_APPPATH'].'config/'.$_ENV['XJ_ENV'].'/routes.php');
}
elseif (is_file($_ENV['XJ_APPPATH'].'config/routes.php'))
{
	include($_ENV['XJ_APPPATH'].'config/routes.php');
}
if (!isset($route_depin))$route_depin = 0;
if (isset($route) && is_array($route)){
	// Loop through the route array looking for wild-cards
	foreach ($route as $key => $val)
	{
		$route_depin = $route_depin + 1;
		if ($route_depin > 100){
			xj_sys_show_error('route key['.$key.'] depin error.');
		}
		
		// Convert wild-cards to RegEx
		$key = str_replace(':any', '.*', str_replace(':num', '[0-9]+', $key));
		if (strpos($application_folder, 'task')){
			//xj_sys_show_error('is_array:'.$application_folder);
			//xj_sys_show_error('#^'.$key.'$#,'.$uri);
			//xj_sys_show_error($uri);
		}
		// Does the RegEx match?
		if (preg_match('#^/'.$key.'$#', $uri))
		{
			$uri_new = FALSE;
			$class = FALSE;
			$method = FALSE;
			if (is_string($val)){
				$uri_new = $val;
			}elseif (is_array($val)){
				if (isset($val['uri']))	$uri_new = $val['uri'];
				if (isset($val['application_folder']))	$application_folder = $val['application_folder'];
				if (isset($val['method']))	$method = ucfirst($val['method']);
			}
			// Do we have a back-reference?
			if (strpos($uri_new, '$') !== FALSE AND strpos($key, '(') !== FALSE)
			{
				$uri_new = preg_replace('#^/'.$key.'$#', $uri_new, $uri);
			}
			$uri = '/'.$uri_new;
			//xj_sys_show_error('uri:'.$uri);
			//if (strpos($application_folder, 'task'))
				//xj_sys_show_error('preg_match:'.$application_folder);
			require BASEPATH.'xj_core/XJ.php';
			xj_sys_show_error('#^'.$key.'$#');
			exit(0);
		}
	}	
}
// ------------------------------------------------------------------------

/*
 * ------------------------------------------------------
 *  Load the requested controller（加载应用控制器文件）
 * ------------------------------------------------------
 */
if (empty($class)){
	$class = "Index";
}
$controller_file = $_ENV['XJ_APPPATH'].'controllers'.DIRECTORY_SEPARATOR.$class.'.php';
if (! file_exists($controller_file))
{
	if (isset($_ENV['XJ_PUBPATH'])){
		$controller_file = $_ENV['XJ_PUBPATH'].'controllers'.DIRECTORY_SEPARATOR.$class.'.php';
	}
	if (! file_exists($controller_file)){
		//show_error(BASEPATH.'xj_core/'.$class.'.php');
		if (file_exists(BASEPATH.'xj_core/controllers/'.$class.'.php')){
			//show_error('OK');
			require_once(BASEPATH.'xj_core/controllers/'.$class.'.php');
			if (in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE))
			{
				$XJ = new $class();
				call_user_func(array(&$XJ, $method), $id);
				xj_output_display();
				exit(0);
			}
		}
		$e404 = TRUE;
		$message =  "Not load file.[".$_ENV['XJ_APPPATH'].''.$class.".php]";
		xj_sys_show_error($message);
	}
}
else
{
	require_once($controller_file);

	if ( ! class_exists($class, FALSE))// OR $method[0] === '_' OR method_exists('XJ_Controller', $method))
	{
		$e404 = TRUE;
		$message =  "Not load class.[".$class."]";
		xj_sys_show_error($message);
	}
	// WARNING: It appears that there are issues with is_callable() even in PHP 5.2!
	// Furthermore, there are bug reports and feature/change requests related to it
	// that make it unreliable to use in this context. Please, DO NOT change this
	// work-around until a better alternative is available.
	elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE))
	{
		$e404 = TRUE;
		$message =  "Not load method.[".$class.".".$method."]";
		xj_sys_show_error($message);
	}
}

/*
 * ------------------------------------------------------
 *  Instantiate the requested controller
 * ------------------------------------------------------
 */
$XJ = new $class();
require_once(BASEPATH.'xj_core'.DIRECTORY_SEPARATOR.'Loader.php');
$XJ->load =  new XJ_Loader;
require_once(BASEPATH.'xj_core'.DIRECTORY_SEPARATOR.'Config.php');
$XJ->config =  new XJ_Config;
require_once(BASEPATH.'xj_core'.DIRECTORY_SEPARATOR.'Input.php');
$XJ->input =  new XJ_Input;
require_once(BASEPATH.'xj_core'.DIRECTORY_SEPARATOR.'Output.php');
$XJ->output =  new XJ_Output;

$XJ->method = $method;

$ret = TRUE;
if ( in_array(strtolower('Init'), array_map('strtolower', get_class_methods($class)), TRUE)){
	$ret = call_user_func(array(&$XJ, 'Init'), $id);
}

/*
 * ------------------------------------------------------
 *  Call the requested method
 * ------------------------------------------------------
 */
$ret !== FALSE && call_user_func(array(&$XJ, $method), $id);

if ( in_array(strtolower('Destroy'), array_map('strtolower', get_class_methods($class)), TRUE)){
	call_user_func(array(&$XJ, 'Destroy'), $id);
}

/*
 * ------------------------------------------------------
 *  Send the final rendered output to the browser
 * ------------------------------------------------------
 */
xj_output_display();

/*
 * ------------------------------------------------------
 *  Close the DB connection if one exists
 * ------------------------------------------------------
 */
if (isset($XJ->db))
{
	$XJ->db = NULL;
}
exit(0);